#include "AdminGUI.hpp"
#include "tools/ReadAndWeite.hpp"
#include <QBitmap>
#include <QDebug>
#include <QDir>
#include <QEvent>
#include <QFile>
#include <QFileInfo>
#include <QFontDatabase>
#include <QHeaderView>
#include <QInputDialog>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMouseEvent>
#include <QPainter>
#include <qdebug.h>
#include <string>

AdminGUI::AdminGUI(QWidget *parent) : QWidget(parent), adminId_("admin") {
  setupUI();
  setupSignalsAndSlots();
  refreshApiManagement(); // 默认显示API管理页面
}

AdminGUI::~AdminGUI() {
  // 释放资源或保存数据
  saveApiKeys();
  saveUsers();
}

void AdminGUI::setAdminId(const QString &adminId) {
  adminId_ = adminId;
  // 可以根据管理员ID加载不同的配置或权限
}

void AdminGUI::setupUI() {
  // 设置主窗口属性
  setMinimumSize(2580, 1600);
  setWindowTitle("AI聊天客户端 - 管理后台");

  // 创建主布局
  mainLayout_ = new QHBoxLayout(this);
  mainLayout_->setContentsMargins(0, 0, 0, 0);
  mainLayout_->setSpacing(0);

  // 设置左侧边栏
  setupSidebar();

  // 设置右侧内容区
  contentWidget_ = new QWidget(this);
  contentLayout_ = new QVBoxLayout(contentWidget_);
  contentLayout_->setContentsMargins(0, 0, 0, 0);
  contentLayout_->setSpacing(0);

  // 设置顶部工具栏
  setupHeader();

  // 设置主内容区
  setupMainContent();

  contentLayout_->addWidget(headerWidget_);
  contentLayout_->addWidget(mainContentStack_);
  mainLayout_->addWidget(sidebarWidget_);
  mainLayout_->addWidget(contentWidget_);

  // 设置左右区域的比例
  mainLayout_->setStretch(0, 1);
  mainLayout_->setStretch(1, 5);

  // 加载样式表
  loadStyleSheet();

  // 默认显示API管理页面
  mainContentStack_->setCurrentWidget(apiManagementPage_);
  setActiveSidebarItem(apiManagementBtn_);
}

void AdminGUI::setupSidebar() {
  // 创建侧边栏
  sidebarWidget_ = new QWidget(this);
  sidebarWidget_->setObjectName("sidebarWidget");
  sidebarWidget_->setMaximumWidth(250);
  sidebarLayout_ = new QVBoxLayout(sidebarWidget_);
  sidebarLayout_->setContentsMargins(0, 0, 0, 0);
  sidebarLayout_->setSpacing(0);

  // 添加Logo
  logoLabel_ = new QLabel(sidebarWidget_);
  logoLabel_->setObjectName("logoLabel");
  logoLabel_->setPixmap(QPixmap(
      ":/opensource/Light-Year-Admin-Using-Iframe-v4/images/logo-sidebar.png"));
  logoLabel_->setAlignment(Qt::AlignCenter);
  logoLabel_->setMinimumHeight(60);
  sidebarLayout_->addWidget(logoLabel_);

  // 添加侧边栏菜单项
  // API管理
  apiManagementBtn_ = createSidebarItem("API管理", "mdi-key-variant");
  sidebarLayout_->addWidget(apiManagementBtn_);

  // 用户管理
  userManagementBtn_ =
      createSidebarItem("用户管理", "mdi-account-group-outline");
  sidebarLayout_->addWidget(userManagementBtn_);

  // 添加弹性空间
  QWidget *spacer = new QWidget();
  spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
  sidebarLayout_->addWidget(spacer);
}

// 创建侧边栏菜单项辅助方法
QWidget *AdminGUI::createSidebarItem(const QString &text,
                                     const QString &iconClass) {
  QWidget *item = new QWidget();
  item->setObjectName("sidebarItem");
  item->setMinimumHeight(50);

  QHBoxLayout *layout = new QHBoxLayout(item);
  layout->setContentsMargins(15, 0, 15, 0);

  QLabel *iconLabel = new QLabel();
  iconLabel->setObjectName("sidebarIcon");

  // 根据iconClass设置图标 - 使用简单的文字代替Material Design图标
  if (iconClass == "mdi-home-outline") {
    iconLabel->setText("🏠"); // 家图标
  } else if (iconClass == "mdi-key-variant") {
    iconLabel->setText("🔑"); // 钥匙图标
  } else if (iconClass == "mdi-brain") {
    iconLabel->setText("🧠"); // 大脑图标
  } else if (iconClass == "mdi-text-box-outline") {
    iconLabel->setText("📋"); // 文本框图标
  } else if (iconClass == "mdi-account-group-outline") {
    iconLabel->setText("👥"); // 用户组图标
  } else {
    iconLabel->setText("•"); // 默认图标
  }

  // 设置字体为Material Design Icons
  QFont iconFont = iconLabel->font();
  iconFont.setFamily("JetBrains Mono");
  iconFont.setPointSize(28);
  iconLabel->setFont(iconFont);
  iconLabel->setMinimumSize(48, 48);
  iconLabel->setAlignment(Qt::AlignCenter);

  QLabel *textLabel = new QLabel(text);
  textLabel->setObjectName("sidebarText");

  layout->addWidget(iconLabel);
  layout->addWidget(textLabel);
  layout->addStretch();

  return item;
}

void AdminGUI::setupHeader() {
  headerWidget_ = new QWidget(contentWidget_);
  headerWidget_->setObjectName("headerWidget");
  headerWidget_->setMinimumHeight(60);
  headerLayout_ = new QHBoxLayout(headerWidget_);
  headerLayout_->setContentsMargins(15, 0, 15, 0);

  // 菜单折叠按钮
  menuToggleBtn_ = new QToolButton();
  menuToggleBtn_->setObjectName("menuToggleBtn");

  // 使用JetBrains Mono字体
  QFont iconFont;
  iconFont.setFamily("JetBrains Mono");
  iconFont.setPointSize(28);
  menuToggleBtn_->setFont(iconFont);
  menuToggleBtn_->setText("☰"); // 菜单图标

  menuToggleBtn_->setMinimumSize(80, 80);
  menuToggleBtn_->setStyleSheet(
      "background-color: transparent; border: none; color: #6c757d;");

  // 页面标题
  pageTitleLabel_ = new QLabel("首页");
  pageTitleLabel_->setObjectName("pageTitleLabel");
  pageTitleLabel_->setStyleSheet(
      "font-size: 18px; font-weight: 500; color: #343a40;");

  // 管理员信息按钮
  adminProfileBtn_ = new QToolButton();
  adminProfileBtn_->setObjectName("adminProfileBtn");

  // 创建带头像的管理员按钮
  QHBoxLayout *profileLayout = new QHBoxLayout(adminProfileBtn_);
  profileLayout->setContentsMargins(8, 0, 8, 0);
  profileLayout->setSpacing(8);

  QLabel *avatarLabel = new QLabel();
  avatarLabel->setFixedSize(36, 36);
  QPixmap avatar(
      ":/opensource/Light-Year-Admin-Using-Iframe-v4/images/users/avatar.jpg");
  if (!avatar.isNull()) {
    avatar =
        avatar.scaled(36, 36, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    // 创建圆形头像
    QBitmap mask(36, 36);
    QPainter painter(&mask);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.fillRect(0, 0, 36, 36, Qt::white);
    painter.setBrush(Qt::black);
    painter.drawEllipse(0, 0, 36, 36);
    avatar.setMask(mask);
    avatarLabel->setPixmap(avatar);
  } else {
    avatarLabel->setText("\uF013D"); // 用户图标
    avatarLabel->setFont(iconFont);
    avatarLabel->setAlignment(Qt::AlignCenter);
    avatarLabel->setStyleSheet(
        "background-color: #e9ecef; border-radius: 18px; color: #6c757d;");
  }

  QLabel *adminLabel = new QLabel("管理员");

  profileLayout->addWidget(avatarLabel);
  profileLayout->addWidget(adminLabel);

  adminProfileBtn_->setMinimumSize(240, 80);
  adminProfileBtn_->setStyleSheet("background-color: transparent; border: "
                                  "none; text-align: left; padding: 0;");

  headerLayout_->addWidget(menuToggleBtn_);
  headerLayout_->addWidget(pageTitleLabel_);
  headerLayout_->addStretch();
  headerLayout_->addWidget(adminProfileBtn_);
}

void AdminGUI::setupMainContent() {
  mainContentStack_ = new QStackedWidget(contentWidget_);
  mainContentStack_->setObjectName("mainContentStack");

  // 创建各个页面
  apiManagementPage_ = createApiManagementPage();
  userManagementPage_ = createUserManagementPage();

  // 添加到堆栈小部件
  mainContentStack_->addWidget(apiManagementPage_);
  mainContentStack_->addWidget(userManagementPage_);
}

QWidget *AdminGUI::createApiManagementPage() {
  QWidget *page = new QWidget();
  page->setObjectName("apiManagementPage");

  QVBoxLayout *layout = new QVBoxLayout(page);
  layout->setContentsMargins(15, 15, 15, 15);

  // 标题
  QLabel *title = new QLabel("API密钥管理");
  title->setObjectName("pageTitle");

  // 工具栏
  QWidget *toolbar = new QWidget();
  QHBoxLayout *toolbarLayout = new QHBoxLayout(toolbar);
  toolbarLayout->setContentsMargins(0, 0, 0, 0); // 使用JetBrains Mono字体
  QFont iconFont;
  iconFont.setFamily("JetBrains Mono");
  iconFont.setPointSize(24);

  addApiKeyBtn_ = new QPushButton("添加API密钥");
  addApiKeyBtn_->setFont(iconFont);
  addApiKeyBtn_->setText("+ 添加API密钥");
  addApiKeyBtn_->setMinimumWidth(120);

  editApiKeyBtn_ = new QPushButton("编辑");
  editApiKeyBtn_->setFont(iconFont);
  editApiKeyBtn_->setText("✎ 编辑");
  editApiKeyBtn_->setStyleSheet("background-color: #17a2b8;");

  deleteApiKeyBtn_ = new QPushButton("删除");
  deleteApiKeyBtn_->setFont(iconFont);
  deleteApiKeyBtn_->setText("✕ 删除");
  deleteApiKeyBtn_->setStyleSheet("background-color: #dc3545;");

  toolbarLayout->addWidget(addApiKeyBtn_);
  toolbarLayout->addWidget(editApiKeyBtn_);
  toolbarLayout->addWidget(deleteApiKeyBtn_);
  toolbarLayout->addStretch();

  // API密钥表格
  apiKeysTable_ = new QTableWidget(0, 4);
  apiKeysTable_->setObjectName("apiKeysTable");
  apiKeysTable_->setHorizontalHeaderLabels(
      {"名称", "API密钥", "服务提供商", "状态"});
  apiKeysTable_->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
  apiKeysTable_->setEditTriggers(QAbstractItemView::NoEditTriggers);
  apiKeysTable_->setSelectionBehavior(QAbstractItemView::SelectRows);
  apiKeysTable_->setAlternatingRowColors(true);
  apiKeysTable_->verticalHeader()->setVisible(false);

  layout->addWidget(title);
  layout->addWidget(toolbar);
  layout->addWidget(apiKeysTable_);

  return page;
}

QWidget *AdminGUI::createUserManagementPage() {
  QWidget *page = new QWidget();
  page->setObjectName("userManagementPage");

  QVBoxLayout *layout = new QVBoxLayout(page);
  layout->setContentsMargins(15, 15, 15, 15);

  // 标题
  QLabel *title = new QLabel("用户管理");
  title->setObjectName("pageTitle");

  // 工具栏
  QWidget *toolbar = new QWidget();
  QHBoxLayout *toolbarLayout = new QHBoxLayout(toolbar);
  toolbarLayout->setContentsMargins(0, 0, 0, 0); // 使用JetBrains Mono字体
  QFont iconFont;
  iconFont.setFamily("JetBrains Mono");
  iconFont.setPointSize(28);

  addUserBtn_ = new QPushButton("添加用户");
  addUserBtn_->setFont(iconFont);
  addUserBtn_->setText("+ 添加用户");
  addUserBtn_->setMinimumWidth(120);

  editUserBtn_ = new QPushButton("编辑");
  editUserBtn_->setFont(iconFont);
  editUserBtn_->setText("✎ 编辑");
  editUserBtn_->setStyleSheet("background-color: #17a2b8;");

  deleteUserBtn_ = new QPushButton("删除");
  deleteUserBtn_->setFont(iconFont);
  deleteUserBtn_->setText("✕ 删除");
  deleteUserBtn_->setStyleSheet("background-color: #dc3545;");

  blockUserBtn_ = new QPushButton("封禁/解封");
  blockUserBtn_->setFont(iconFont);
  blockUserBtn_->setText("⚠ 封禁/解封");
  blockUserBtn_->setStyleSheet("background-color: #ffc107; color: #212529;");

  toolbarLayout->addWidget(addUserBtn_);
  toolbarLayout->addWidget(editUserBtn_);
  toolbarLayout->addWidget(deleteUserBtn_);
  toolbarLayout->addWidget(blockUserBtn_);
  toolbarLayout->addStretch();

  // 用户表格
  usersTable_ = new QTableWidget(0, 5);
  usersTable_->setObjectName("usersTable");
  usersTable_->setHorizontalHeaderLabels(
      {"用户名", "电子邮箱", "注册时间", "最后登录", "状态"});
  usersTable_->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
  usersTable_->setEditTriggers(QAbstractItemView::NoEditTriggers);
  usersTable_->setSelectionBehavior(QAbstractItemView::SelectRows);
  usersTable_->setAlternatingRowColors(true);
  usersTable_->verticalHeader()->setVisible(false);

  layout->addWidget(title);
  layout->addWidget(toolbar);
  layout->addWidget(usersTable_);

  return page;
}

void AdminGUI::setupSignalsAndSlots() {
  // 连接左侧菜单事件（使用事件过滤器）
  apiManagementBtn_->installEventFilter(this);
  userManagementBtn_->installEventFilter(this);

  // 连接API管理页面按钮信号
  connect(addApiKeyBtn_, &QPushButton::clicked, this,
          &AdminGUI::onAddApiKeyClicked);
  connect(editApiKeyBtn_, &QPushButton::clicked, this,
          &AdminGUI::onEditApiKeyClicked);
  connect(deleteApiKeyBtn_, &QPushButton::clicked, this,
          &AdminGUI::onDeleteApiKeyClicked);

  // 连接用户管理页面按钮信号
  connect(addUserBtn_, &QPushButton::clicked, this,
          &AdminGUI::onAddUserClicked);
  connect(editUserBtn_, &QPushButton::clicked, this,
          &AdminGUI::onEditUserClicked);
  connect(deleteUserBtn_, &QPushButton::clicked, this,
          &AdminGUI::onDeleteUserClicked);
  connect(blockUserBtn_, &QPushButton::clicked, this,
          &AdminGUI::onBlockUserClicked);
}

void AdminGUI::loadStyleSheet() {
  // 加载主样式表
  QFile style_file(
      ":/opensource/Light-Year-Admin-Using-Iframe-v4/css/style.min.css");
  QFile bootstrap_file(
      ":/opensource/Light-Year-Admin-Using-Iframe-v4/css/bootstrap.min.css");

  QString styleSheet;

  if (bootstrap_file.open(QFile::ReadOnly)) {
    styleSheet += QString::fromUtf8(bootstrap_file.readAll());
    bootstrap_file.close();
  }

  if (style_file.open(QFile::ReadOnly)) {
    styleSheet += QString::fromUtf8(style_file.readAll());
    style_file.close();
  }

  // 自定义Qt特定样式
  styleSheet +=
      "QWidget#sidebarWidget { background-color: #343a40; color: white; }"
      "QWidget#headerWidget { background-color: #ffffff; border-bottom: 1px "
      "solid #dee2e6; }"
      "QLabel#logoLabel { padding: 15px; }"
      "QWidget#sidebarItem { color: #adb5bd; border-radius: 3px; margin: 2px "
      "10px; }"
      "QWidget#sidebarItem:hover { background-color: #3a4047; color: white; }"
      "QLabel#pageTitle { font-size: 20px; font-weight: bold; margin-bottom: "
      "15px; }"
      "QFrame#statsCard { background-color: white; border-radius: 5px; "
      "padding: 15px; margin: 5px; border: 1px solid #e5e5e5; }"
      "QLabel#statsValue { font-size: 24px; font-weight: bold; color: #007bff; "
      "}"
      "QLabel#statsTitle { color: #6c757d; }"
      "QLabel#statsIcon { color: #007bff; background-color: "
      "rgba(0,123,255,0.1); border-radius: 25px; margin-right: 15px; padding: "
      "10px; font-size: 20px; min-width: 50px; min-height: 50px; }"
      "QPushButton { background-color: #007bff; color: white; border: none; "
      "border-radius: 3px; padding: 8px 16px; font-weight: 500; }"
      "QPushButton:hover { background-color: #0069d9; }"
      "QPushButton:pressed { background-color: #0062cc; }"
      "QTableWidget { border: none; background-color: white; border-radius: "
      "3px; }"
      "QTableWidget::item { padding: 8px; border-bottom: 1px solid #f2f2f2; }"
      "QTableWidget::item:selected { background-color: #e8f0fe; color: "
      "#212529; }"
      "QHeaderView::section { background-color: #f8f9fa; padding: 10px; "
      "border: none; font-weight: bold; }"
      "QWidget#apiManagementPage, QWidget#userManagementPage {"
      "  background-color: white; border-radius: 5px; padding: 15px; "
      "margin-top: 15px; border: 1px solid #e5e5e5;"
      "}"
      "QLabel#cardTitle { font-size: 16px; font-weight: bold; margin-bottom: "
      "10px; }";

  setStyleSheet(styleSheet);
}

void AdminGUI::setActiveSidebarItem(QWidget *item) {
  // 重置所有菜单项的样式
  QList<QWidget *> items = {apiManagementBtn_, userManagementBtn_};

  for (QWidget *menuItem : items) {
    menuItem->setProperty("active", false);
    menuItem->setStyleSheet("background-color: transparent;");
  }

  // 设置活动菜单项的样式
  item->setProperty("active", true);
  item->setStyleSheet("background-color: #3a4047; color: white;");

  activeSidebarItem_ = item;
}

bool AdminGUI::eventFilter(QObject *watched, QEvent *event) {
  if (event->type() == QEvent::MouseButtonPress) {
    if (watched == apiManagementBtn_) {
      onApiManagementClicked();
      return true;
    } else if (watched == userManagementBtn_) {
      onUserManagementClicked();
      return true;
    }
  }
  return QWidget::eventFilter(watched, event);
}

// 侧边栏菜单项点击事件
void AdminGUI::onApiManagementClicked() {
  mainContentStack_->setCurrentWidget(apiManagementPage_);
  setActiveSidebarItem(apiManagementBtn_);
  pageTitleLabel_->setText("API管理");
  refreshApiManagement();
}

void AdminGUI::onUserManagementClicked() {
  mainContentStack_->setCurrentWidget(userManagementPage_);
  setActiveSidebarItem(userManagementBtn_);
  pageTitleLabel_->setText("用户管理");
  refreshUserManagement();
}

void AdminGUI::refreshApiManagement() {
  // 清空表格
  apiKeysTable_->setRowCount(0);

  // 加载API密钥数据
  loadApiKeys();
}

void AdminGUI::refreshUserManagement() {
  // 清空表格
  usersTable_->setRowCount(0);

  // 加载用户数据
  loadUsers();
}

// 数据操作方法
void AdminGUI::loadApiKeys() {
  // 清空表格
  apiKeysTable_->setRowCount(0);

  // 查找所有api_key开头的JSON文件
  QDir resourceDir("/home/ccy/code_workspace/cpp_finall/resource");
  QStringList apiFiles =
      resourceDir.entryList(QStringList() << "api_key*.json", QDir::Files);

  int row = 0;

  // 兼容处理：如果没有api_key开头的文件，使用原有逻辑
  if (apiFiles.isEmpty()) {
    // 使用原有的api_key.json
    std::string filePath =
        "/home/ccy/code_workspace/cpp_finall/resource/api_key.json";
    nlohmann::json jsonData;
    try {
      read_from_file(filePath, jsonData);

      // 获取API键和模型URL
      std::string api_key = jsonData["api_key"];
      std::string selected_model = jsonData.contains("selected_model")
                                       ? jsonData["selected_model"]
                                       : "web_curl_1";
      api_k = api_key; // 保存第一个API密钥到成员变量

      // 添加API密钥到表格
      apiKeysTable_->insertRow(row);
      apiKeysTable_->setItem(row, 0, new QTableWidgetItem("api_key"));

      // 隐藏部分API密钥内容
      QString maskedKey = QString::fromStdString(api_key).left(4) + "..." +
                          QString::fromStdString(api_key).right(4);
      apiKeysTable_->setItem(row, 1, new QTableWidgetItem(maskedKey));

      // 服务提供商
      apiKeysTable_->setItem(row, 2, new QTableWidgetItem("DeepSeek"));

      // 状态
      apiKeysTable_->setItem(row, 3, new QTableWidgetItem("有效"));

      row++;
    } catch (const std::exception &e) {
      qDebug() << "加载API密钥文件失败:" << e.what();
    }
  } else {
    // 加载所有api_key开头的文件
    for (const QString &fileName : apiFiles) {
      std::string filePath =
          resourceDir.absoluteFilePath(fileName).toStdString();
      nlohmann::json jsonData;

      try {
        read_from_file(filePath, jsonData);

        // 获取API密钥信息
        std::string api_key = jsonData["api_key"];

        // 如果是第一个API密钥，保存到成员变量
        if (row == 0) {
          api_k = api_key;
        }

        // 获取API名称
        std::string api_name = "未命名";
        if (jsonData.contains("api_name")) {
          api_name = jsonData["api_name"];
        } else {
          // 从文件名获取
          api_name = fileName.toStdString();
          api_name = api_name.substr(0, api_name.find(".json"));
        }

        // 获取服务提供商
        std::string provider = "未知";
        if (jsonData.contains("provider")) {
          provider = jsonData["provider"];
        } else {
          // 根据名称判断服务提供商
          QString name = QString::fromStdString(api_name);
          if (name.contains("openai", Qt::CaseInsensitive)) {
            provider = "OpenAI";
          } else if (name.contains("deepseek", Qt::CaseInsensitive)) {
            provider = "DeepSeek";
          }
        }

        // 添加到表格
        apiKeysTable_->insertRow(row);
        apiKeysTable_->setItem(
            row, 0, new QTableWidgetItem(QString::fromStdString(api_name)));

        // 隐藏部分API密钥内容
        QString maskedKey = QString::fromStdString(api_key).left(4) + "..." +
                            QString::fromStdString(api_key).right(4);
        apiKeysTable_->setItem(row, 1, new QTableWidgetItem(maskedKey));

        // 服务提供商
        apiKeysTable_->setItem(
            row, 2, new QTableWidgetItem(QString::fromStdString(provider)));

        // 状态
        apiKeysTable_->setItem(row, 3, new QTableWidgetItem("有效"));

        // 保存文件名作为用户数据，以便编辑或删除时使用
        apiKeysTable_->item(row, 0)->setData(Qt::UserRole, fileName);

        row++;
      } catch (const std::exception &e) {
        qDebug() << "加载API密钥文件失败:" << fileName << e.what();
      }
    }
  }
}

void AdminGUI::saveApiKeys() {
  // 获取表格中的所有API密钥
  int rowCount = apiKeysTable_->rowCount();

  // 兼容处理：保留原有的api_key.json以便和现有系统兼容
  QString defaultFilePath =
      "/home/ccy/code_workspace/cpp_finall/resource/api_key.json";
  QString selectedModel = "web_curl_1"; // 默认值

  // 如果表格中存在数据，使用第一行的API密钥更新api_key.json
  if (rowCount > 0) {
    QString keyName = apiKeysTable_->item(0, 0)->text();
    QString maskedKey = apiKeysTable_->item(0, 1)->text();
    QString provider = apiKeysTable_->item(0, 2)->text();

    // 读取完整密钥
    QString fileName = apiKeysTable_->item(0, 0)->data(Qt::UserRole).toString();
    std::string keyValue = api_k; // 默认使用成员变量中的密钥

    if (!fileName.isEmpty()) {
      // 从对应的文件中读取完整密钥
      std::string filePath = "/home/ccy/code_workspace/cpp_finall/resource/" +
                             fileName.toStdString();
      nlohmann::json jsonData;
      try {
        read_from_file(filePath, jsonData);
        if (jsonData.contains("api_key")) {
          keyValue = jsonData["api_key"];
        }
      } catch (const std::exception &e) {
        qDebug() << "读取API密钥文件失败:" << fileName << e.what();
      }
    }

    // 更新api_key.json
    nlohmann::json apiJson;
    apiJson["api_key"] = keyValue;
    apiJson["selected_model"] = selectedModel.toStdString();

    // 保存api_key.json
    try {
      write_to_file(defaultFilePath.toStdString(), apiJson);
    } catch (const std::exception &e) {
      qDebug() << "无法保存API密钥文件:" << e.what();
    }
  }

  // 遍历表格，更新或删除对应的API密钥文件
  QDir resourceDir("/home/ccy/code_workspace/cpp_finall/resource");
  QStringList existingApiFiles =
      resourceDir.entryList(QStringList() << "api_key*.json", QDir::Files);

  // 创建一个集合来跟踪表格中的文件
  QSet<QString> tableFiles;

  // 更新表格中的每一行对应的文件
  for (int row = 0; row < rowCount; row++) {
    QString keyName = apiKeysTable_->item(row, 0)->text();
    QString maskedKey = apiKeysTable_->item(row, 1)->text();
    QString provider = apiKeysTable_->item(row, 2)->text();
    QString fileName =
        apiKeysTable_->item(row, 0)->data(Qt::UserRole).toString();

    // 如果没有关联文件名，创建一个新文件
    if (fileName.isEmpty()) {
      // 生成新的文件名
      int maxNumber = 0;
      for (const QString &file : existingApiFiles) {
        QString numStr = file;
        numStr.remove("api_key");
        numStr.remove(".json");
        bool ok;
        int num = numStr.toInt(&ok);
        if (ok && num > maxNumber) {
          maxNumber = num;
        }
      }

      fileName = QString("api_key%1.json").arg(maxNumber + 1);
      apiKeysTable_->item(row, 0)->setData(Qt::UserRole, fileName);
    }

    tableFiles.insert(fileName);

    // 更新API密钥文件
    nlohmann::json apiJson;
    apiJson["api_name"] = keyName.toStdString();
    apiJson["provider"] = provider.toStdString();

    // 尝试从文件中读取完整的API密钥
    std::string filePath = "/home/ccy/code_workspace/cpp_finall/resource/" +
                           fileName.toStdString();
    try {
      // 如果文件已存在，读取API密钥
      if (QFile::exists(QString::fromStdString(filePath))) {
        nlohmann::json existingJson;
        read_from_file(filePath, existingJson);
        if (existingJson.contains("api_key")) {
          apiJson["api_key"] = existingJson["api_key"];
        }
      }
      // 如果是第一行，使用成员变量中的密钥
      else if (row == 0) {
        apiJson["api_key"] = api_k;
      }

      // 保存文件
      write_to_file(filePath, apiJson);
    } catch (const std::exception &e) {
      qDebug() << "无法保存API密钥文件:" << fileName << e.what();
    }
  }

  // 发出配置更改信号
  emit apiConfigChanged();
}

void AdminGUI::loadUsers() {
  // 实现加载用户数据的逻辑
  // 遍历resource/user目录下的所有用户JSON文件

  QDir userDir("/home/ccy/code_workspace/cpp_finall/resource/user");
  if (userDir.exists()) {
    QStringList userFiles =
        userDir.entryList(QStringList() << "*.json", QDir::Files);

    for (const QString &fileName : userFiles) {
      // 跳过用户索引文件
      if (fileName == "users.json") {
        continue;
      }

      // 读取用户JSON文件
      nlohmann::json userJson;
      std::string filePath = userDir.absoluteFilePath(fileName).toStdString();
      read_from_file(filePath, userJson);

      if (userJson.contains("user_name") && userJson.contains("user_email")) {
        int row = usersTable_->rowCount();
        usersTable_->insertRow(row);

        // 用户名
        QString userName =
            QString::fromStdString(userJson["user_name"].get<std::string>());
        usersTable_->setItem(row, 0, new QTableWidgetItem(userName));

        // 电子邮箱
        QString userEmail =
            QString::fromStdString(userJson["user_email"].get<std::string>());
        usersTable_->setItem(row, 1, new QTableWidgetItem(userEmail));

        // 注册时间（从文件创建时间获取）
        QFileInfo fileInfo(QString::fromStdString(filePath));
        QDateTime creationTime = fileInfo.birthTime();
        usersTable_->setItem(
            row, 2,
            new QTableWidgetItem(creationTime.toString("yyyy-MM-dd hh:mm:ss")));

        // 最后登录时间（从文件修改时间获取）
        QDateTime lastModified = fileInfo.lastModified();
        usersTable_->setItem(
            row, 3,
            new QTableWidgetItem(lastModified.toString("yyyy-MM-dd hh:mm:ss")));

        // 读取用户状态
        QString status = "正常";
        if (userJson.contains("status")) {
          std::string userStatus = userJson["status"].get<std::string>();
          if (userStatus == "banned") {
            status = "已封禁";
          }
        }

        usersTable_->setItem(row, 4, new QTableWidgetItem(status));

        // 存储用户ID到表格项的数据中，方便后续操作
        usersTable_->item(row, 0)->setData(
            Qt::UserRole,
            QString::fromStdString(userJson["user_id"].get<std::string>()));
      }
    }
  } else {
    qDebug() << "用户目录不存在";
  }
}

void AdminGUI::saveUsers() {
  qDebug() << "保存用户数据";

  // 获取用户表格中的所有数据
  int rowCount = usersTable_->rowCount();
  for (int row = 0; row < rowCount; ++row) {
    // 获取用户信息
    QString username = usersTable_->item(row, 0)->text();
    QString email = usersTable_->item(row, 1)->text();
    QString status = usersTable_->item(row, 4)->text();
    QString userId = usersTable_->item(row, 0)->data(Qt::UserRole).toString();

    // 如果没有用户ID，则生成一个
    if (userId.isEmpty()) {
      // 生成一个随机六位数作为用户ID
      srand(QDateTime::currentDateTime().toSecsSinceEpoch() + row);
      int randomNumber =
          100000 + (rand() % 900000); // 生成100000-999999之间的随机六位数
      userId = QString::number(randomNumber);
      usersTable_->item(row, 0)->setData(Qt::UserRole, userId);
    }

    // 准备JSON数据
    nlohmann::json userJson;

    // 首先尝试读取现有文件，保留其他信息
    std::string userFilePath =
        "/home/ccy/code_workspace/cpp_finall/resource/user/" +
        userId.toStdString() + ".json";

    try {
      // 尝试读取现有文件
      read_from_file(userFilePath, userJson);
    } catch (const std::exception &e) {
      // 如果文件不存在，创建新的JSON对象
      qDebug() << "创建新用户文件: " << e.what();
    }

    // 更新基本信息
    userJson["user_id"] = userId.toStdString();
    userJson["user_name"] = username.toStdString();
    userJson["user_email"] = email.toStdString();

    // 更新状态
    std::string jsonStatus = (status == "已封禁") ? "banned" : "active";
    userJson["status"] = jsonStatus;

    // 保存到文件
    try {
      write_to_file(userFilePath, userJson);
    } catch (const std::exception &e) {
      qDebug() << "无法保存用户数据文件:" << e.what();
    }
  }

  // 更新用户索引文件 (可选)
  try {
    // 创建或更新 users.json 文件，包含所有用户的ID列表
    nlohmann::json usersIndexJson;
    usersIndexJson["user_count"] = rowCount;

    nlohmann::json usersList = nlohmann::json::array();
    for (int row = 0; row < rowCount; ++row) {
      QString userId = usersTable_->item(row, 0)->data(Qt::UserRole).toString();
      if (!userId.isEmpty()) {
        usersList.push_back(userId.toStdString());
      }
    }
    usersIndexJson["users"] = usersList;

    std::string indexFilePath =
        "/home/ccy/code_workspace/cpp_finall/resource/user/users.json";
    write_to_file(indexFilePath, usersIndexJson);

  } catch (const std::exception &e) {
    qDebug() << "无法保存用户索引文件:" << e.what();
  }
}

// API管理页面事件
void AdminGUI::onAddApiKeyClicked() {
  bool ok;
  QString name = QInputDialog::getText(
      this, "添加API密钥",
      "API密钥名称(如openai, deepseek等):", QLineEdit::Normal, "", &ok);
  if (ok && !name.isEmpty()) {
    QString key = QInputDialog::getText(
        this, "添加API密钥", "API密钥值:", QLineEdit::Normal, "", &ok);
    if (ok && !key.isEmpty()) {
      // 添加到表格
      int row = apiKeysTable_->rowCount();
      apiKeysTable_->insertRow(row);

      apiKeysTable_->setItem(row, 0, new QTableWidgetItem(name));

      // 显示掩码
      QString maskedKey = key.left(4) + "..." + key.right(4);
      apiKeysTable_->setItem(row, 1, new QTableWidgetItem(maskedKey));

      // 服务提供商
      QString provider = "未知";
      if (name.contains("openai", Qt::CaseInsensitive)) {
        provider = "OpenAI";
      } else if (name.contains("deepseek", Qt::CaseInsensitive)) {
        provider = "DeepSeek";
      }
      apiKeysTable_->setItem(row, 2, new QTableWidgetItem(provider));

      apiKeysTable_->setItem(row, 3, new QTableWidgetItem("有效"));

      // 生成新的API密钥文件名
      QDir resourceDir("/home/ccy/code_workspace/cpp_finall/resource");
      QStringList apiFiles =
          resourceDir.entryList(QStringList() << "api_key*.json", QDir::Files);

      // 确定新文件的编号
      int maxNumber = 0;
      for (const QString &fileName : apiFiles) {
        // 从文件名中提取数字部分
        QString numStr = fileName;
        numStr.remove("api_key");
        numStr.remove(".json");
        bool ok;
        int num = numStr.toInt(&ok);
        if (ok && num > maxNumber) {
          maxNumber = num;
        }
      }

      // 新文件编号 = 当前最大编号 + 1
      int newNumber = maxNumber + 1;
      QString newFileName = QString("api_key%1.json").arg(newNumber);

      // 创建新的API密钥JSON
      nlohmann::json apiJson;
      apiJson["api_key"] = key.toStdString();
      apiJson["api_name"] = name.toStdString();
      apiJson["provider"] = provider.toStdString();

      // 保存到新文件
      QString filePath =
          "/home/ccy/code_workspace/cpp_finall/resource/" + newFileName;
      try {
        write_to_file(filePath.toStdString(), apiJson);
        QMessageBox::information(this, "添加API密钥",
                                 "API密钥已保存到文件: " + newFileName);
        emit apiConfigChanged();
      } catch (const std::exception &e) {
        qDebug() << "无法保存API密钥文件:" << e.what();
        QMessageBox::critical(this, "错误",
                              QString("无法保存API密钥文件: %1").arg(e.what()));
      }
    }
  }
}

void AdminGUI::onEditApiKeyClicked() {
  int row = apiKeysTable_->currentRow();
  if (row >= 0) {
    QString currentName = apiKeysTable_->item(row, 0)->text();
    QString fileName =
        apiKeysTable_->item(row, 0)->data(Qt::UserRole).toString();

    bool ok;
    QString newName = QInputDialog::getText(this, "编辑API密钥",
                                            "API密钥名称:", QLineEdit::Normal,
                                            currentName, &ok);
    if (ok && !newName.isEmpty()) {
      QString newKey = QInputDialog::getText(
          this, "编辑API密钥", "API密钥值(留空表示不修改):", QLineEdit::Normal,
          "", &ok);
      if (ok) {
        // 更新表格
        apiKeysTable_->setItem(row, 0, new QTableWidgetItem(newName));
        // 保留文件名
        apiKeysTable_->item(row, 0)->setData(Qt::UserRole, fileName);

        // 服务提供商
        QString provider = "未知";
        if (newName.contains("openai", Qt::CaseInsensitive)) {
          provider = "OpenAI";
        } else if (newName.contains("deepseek", Qt::CaseInsensitive)) {
          provider = "DeepSeek";
        }
        apiKeysTable_->setItem(row, 2, new QTableWidgetItem(provider));

        // 如果提供了新的密钥值
        if (!newKey.isEmpty()) {
          // 如果是第一行，更新成员变量
          if (row == 0) {
            api_k = newKey.toStdString();
          }

          // 更新密钥（显示掩码）
          QString maskedKey = newKey.left(4) + "..." + newKey.right(4);
          apiKeysTable_->setItem(row, 1, new QTableWidgetItem(maskedKey));

          // 更新文件中的API密钥
          if (!fileName.isEmpty()) {
            std::string filePath =
                "/home/ccy/code_workspace/cpp_finall/resource/" +
                fileName.toStdString();
            try {
              nlohmann::json apiJson;

              // 尝试读取现有文件
              try {
                read_from_file(filePath, apiJson);
              } catch (const std::exception &e) {
                // 如果文件不存在，创建新的JSON对象
              }

              // 更新数据
              apiJson["api_key"] = newKey.toStdString();
              apiJson["api_name"] = newName.toStdString();
              apiJson["provider"] = provider.toStdString();

              // 保存回文件
              write_to_file(filePath, apiJson);
            } catch (const std::exception &e) {
              qDebug() << "无法更新API密钥文件:" << fileName << e.what();
            }
          }
        }

        // 保存所有API密钥数据
        saveApiKeys();
      }
    }
  } else {
    QMessageBox::information(this, "编辑API密钥",
                             "请先选择一个要编辑的API密钥");
  }
}

void AdminGUI::onDeleteApiKeyClicked() {
  int row = apiKeysTable_->currentRow();
  if (row >= 0) {
    QString keyName = apiKeysTable_->item(row, 0)->text();
    QString fileName =
        apiKeysTable_->item(row, 0)->data(Qt::UserRole).toString();

    QMessageBox::StandardButton reply = QMessageBox::question(
        this, "删除API密钥",
        QString("确定要删除API密钥 \"%1\" 吗？").arg(keyName),
        QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes) {
      // 如果存在对应的文件，删除它
      if (!fileName.isEmpty()) {
        QString filePath =
            "/home/ccy/code_workspace/cpp_finall/resource/" + fileName;
        QFile file(filePath);
        if (file.exists()) {
          if (!file.remove()) {
            qDebug() << "无法删除API密钥文件:" << filePath;
          } else {
            qDebug() << "成功删除API密钥文件:" << filePath;
          }
        }
      }

      // 从表格中移除
      apiKeysTable_->removeRow(row);

      // 如果当前删除的是第一行，并且还有其他密钥，则更新成员变量
      if (row == 0 && apiKeysTable_->rowCount() > 0) {
        // 尝试读取新的第一行对应的文件，更新成员变量
        QString newFirstFileName =
            apiKeysTable_->item(0, 0)->data(Qt::UserRole).toString();
        if (!newFirstFileName.isEmpty()) {
          std::string filePath =
              "/home/ccy/code_workspace/cpp_finall/resource/" +
              newFirstFileName.toStdString();
          try {
            nlohmann::json jsonData;
            read_from_file(filePath, jsonData);
            if (jsonData.contains("api_key")) {
              api_k = jsonData["api_key"];
            }
          } catch (const std::exception &e) {
            qDebug() << "无法读取新的主API密钥文件:" << e.what();
          }
        }
      }

      // 保存数据
      saveApiKeys();
      QMessageBox::information(this, "删除API密钥", "API密钥已删除");
    }
  } else {
    QMessageBox::information(this, "删除API密钥",
                             "请先选择一个要删除的API密钥");
  }
}

// 用户管理页面事件
void AdminGUI::onAddUserClicked() {
  // 实现添加用户的逻辑
  qDebug() << "添加用户";

  bool ok;
  QString username = QInputDialog::getText(
      this, "添加用户", "用户名:", QLineEdit::Normal, "", &ok);
  if (ok && !username.isEmpty()) {
    QString email = QInputDialog::getText(
        this, "添加用户", "电子邮箱:", QLineEdit::Normal, "", &ok);
    if (ok) {
      QString password = QInputDialog::getText(
          this, "添加用户", "密码:", QLineEdit::Password, "", &ok);
      if (ok && !password.isEmpty()) {
        // 创建用户目录
        QDir userDir;
        if (!userDir.exists("resource/user/" + username)) {
          userDir.mkpath("resource/user/" + username);
        }

        // 添加到表格
        int row = usersTable_->rowCount();
        usersTable_->insertRow(row);

        usersTable_->setItem(row, 0, new QTableWidgetItem(username));
        usersTable_->setItem(row, 1, new QTableWidgetItem(email));

        QDateTime now = QDateTime::currentDateTime();
        usersTable_->setItem(
            row, 2, new QTableWidgetItem(now.toString("yyyy-MM-dd hh:mm:ss")));
        usersTable_->setItem(
            row, 3, new QTableWidgetItem(now.toString("yyyy-MM-dd hh:mm:ss")));
        usersTable_->setItem(row, 4, new QTableWidgetItem("正常"));

        // 保存用户数据
        saveUsers();

        QMessageBox::information(this, "添加用户", "用户创建成功");
      }
    }
  }
}

void AdminGUI::onEditUserClicked() {
  // 实现编辑用户的逻辑
  int row = usersTable_->currentRow();
  if (row >= 0) {
    QString currentUsername = usersTable_->item(row, 0)->text();
    QString currentEmail = usersTable_->item(row, 1)->text();

    bool ok;
    QString newEmail = QInputDialog::getText(
        this, "编辑用户", "电子邮箱:", QLineEdit::Normal, currentEmail, &ok);
    if (ok) {
      usersTable_->setItem(row, 1, new QTableWidgetItem(newEmail));
      saveUsers();
    }
  } else {
    QMessageBox::information(this, "编辑用户", "请先选择一个要编辑的用户");
  }
}

void AdminGUI::onDeleteUserClicked() {
  // 实现删除用户的逻辑
  int row = usersTable_->currentRow();
  if (row >= 0) {
    QString username = usersTable_->item(row, 0)->text();

    QMessageBox::StandardButton reply = QMessageBox::question(
        this, "删除用户",
        "确定要删除用户 " + username + " 吗？此操作将删除用户的所有数据！",
        QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes) {
      // 删除用户目录
      QDir userDir("resource/user/" + username);
      if (userDir.exists()) {
        userDir.removeRecursively();
      }
      // 删除用户JSON文件
      QString userId = usersTable_->item(row, 0)->data(Qt::UserRole).toString();
      QString userFilePath =
          "/home/ccy/code_workspace/cpp_finall/resource/user/" + userId +
          ".json";
      qDebug() << "删除用户文件:" << userId << userFilePath;
      QFile userFile(userFilePath);
      if (userFile.exists()) {
        if (!userFile.remove()) {
          qDebug() << "无法删除用户文件:" << userFilePath;
        }
      }

      usersTable_->removeRow(row);
      saveUsers();

      QMessageBox::information(this, "删除用户", "用户已删除");
    }
  } else {
    QMessageBox::information(this, "删除用户", "请先选择一个要删除的用户");
  }
}

void AdminGUI::onBlockUserClicked() {
  // 实现封禁/解封用户的逻辑
  int row = usersTable_->currentRow();
  if (row >= 0) {
    QString username = usersTable_->item(row, 0)->text();
    QString currentStatus = usersTable_->item(row, 4)->text();
    QString userId = usersTable_->item(row, 0)->data(Qt::UserRole).toString();

    QString newStatus;
    QString action;
    std::string jsonStatus;

    if (currentStatus == "正常") {
      newStatus = "已封禁";
      action = "封禁";
      jsonStatus = "banned";
    } else {
      newStatus = "正常";
      action = "解封";
      jsonStatus = "active";
    }

    QMessageBox::StandardButton reply = QMessageBox::question(
        this, action + "用户", "确定要" + action + "用户 " + username + " 吗？",
        QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes) {
      // 更新表格显示
      usersTable_->setItem(row, 4, new QTableWidgetItem(newStatus));

      // 更新用户JSON文件
      std::string userFilePath =
          "/home/ccy/code_workspace/cpp_finall/resource/user/" +
          userId.toStdString() + ".json";
      nlohmann::json userJson;
      read_from_file(userFilePath, userJson);

      // 更新状态字段
      userJson["status"] = jsonStatus;

      // 写回文件
      write_to_file(userFilePath, userJson);

      QMessageBox::information(this, action + "用户", "用户已" + action);
    }
  } else {
    QMessageBox::information(this, "操作用户", "请先选择一个用户");
  }
}
